<!DOCTYPE html>
<html lang="en">
	<head>
		<title>STLViewer</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<style>
			body {
				font-family: Monospace;
				background-color: white;
				margin: 0px;
				overflow: hidden;
			}

			#info {
				color: #fff;
				position: absolute;
				top: 10px;
				width: 100%;
				text-align: center;
				z-index: 100;
				display:block;

			}

			a { color: skyblue }
			.button { background:#999; color:#eee; padding:0.2em 0.5em; cursor:pointer }
			.highlight { background:orange; color:#fff; }

			span {
				display: inline-block;
				width: 60px;
				text-align: center;
			}
			#infotab{
				position:fixed;
				z-index:999;
				right:10px;
				bottom:0px;
				max-width:480px;
				word-break: break-all;
			}
			p{
			    margin:5px !important;
			}
		</style>
	</head>
	<body>
		<script src="script/Threejs/build/three.js"></script>
		<script src="../../script/jquery.min.js"></script>
		<script src="script/Threejs/STLLoader.js"></script>
		<script src="script/Threejs/OrbitControls.js"></script>
		<script src="script/Threejs/WebGL.js"></script>
		<script src="script/Threejs/stats.min.js"></script>
		<script src="../../script/ao_module.js"></script>
		<div id="infotab">
			<p id="filename"></p>
			<p id="filepath" style="display:none;"></p>
			<a id="displayFilepath" style="cursor: pointer;" onclick="openThisFileInFM(this);"></a>
			<p>{model_dimension}</p>
			<p id="filesize"></p>
			<div>
				<input type="checkbox" id="showWireframe" name="showWireframe" onchange="setMeshToWireframe(this.checked);">
				<label for="showWireframe">Show Wireframe</label>
			</div>
			<br>
		</div>
		<script>
			//Get file information from the hash info
			var files = ao_module_loadInputFiles();
			var file = "";

			//Rendering materials
			var outlineMaterial = new THREE.MeshBasicMaterial( { color: 0x1f1f1f, side: THREE.BackSide, wireframe: true } );
			var mainMaterial = new THREE.MeshPhongMaterial( { 
				color: 0x70721e, 
				specular: 0x050505, 
				shininess: 100,
			});
			if (files.length > 0){
				file = files[0];
				$("#filename").text(file.filename);
				$("#filepath").text("../../media?file=" + file.filepath);
				$("#displayFilepath").text(file.filepath);

				//Get filesize info
				$.ajax({
					url: "../../system/file_system/getProperties", 
					data: {path: file.filepath},
					success: function(data){
						var filesize = ao_module_utils.formatBytes(data.Filesize, 2);
						$("#filesize").text(filesize);
					}
				});
				
			}

			ao_module_setWindowTitle("STLviewer - " + $("#filename").text().trim());
			var objectSize;
			if ( WEBGL.isWebGLAvailable() === false ) {
				document.body.appendChild( WEBGL.getWebGLErrorMessage() );
			}

			var container, stats;
			var camera, cameraTarget, scene, renderer,controls;
			var filename = $("#filepath").text().trim();
			init();
			animate();
				
			function fillValue(tag,value){
				var newcontent = $("#infotab").html();
				newcontent = newcontent.split("{" + tag + "}").join(value);
				$("#infotab").html(newcontent);
			}
			
			function openThisFileInFM(link){
				var fileLocation = $(link).text();
				
				//Open the file using ao_module function call
				var tmp = fileLocation.split("/");
				var targetFilename = tmp.pop();
				var targetFolder = tmp.join("/");
				ao_module_openPath(targetFolder, targetFilename);

			}

			function round(value){
				return Math.round(value * 100) / 100;
			}

			var stlMesh = undefined;
			function init() {

				container = document.createElement( 'div' );
				document.body.appendChild( container );

				camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 1500 );
				camera.position.set( 0, 30, 30 );
				//cameraTarget = new THREE.Vector3( 0, 0, 0 );

				
				scene = new THREE.Scene();
				scene.background = new THREE.Color( 0xf7f7f7 );
				//scene.fog = new THREE.Fog( 0xc9c9c9, 2, 15 );

				var loader = new THREE.STLLoader();
				
				loader.load( filename, function ( geometry ) {
					var mesh = new THREE.Mesh( geometry, mainMaterial );
					stlMesh = mesh;
					const center = new THREE.Vector3();

					//Scsale it down to original's 10%
					mesh.scale.set( 0.1, 0.1, 0.1 );
					render();
					var bbox = new THREE.Box3().setFromObject(mesh);
					//Move the mesh to scene center
					console.log(bbox);
					mesh.updateMatrixWorld();
					console.log((bbox.max.x - bbox.min.x));
					mesh.rotateOnAxis(new THREE.Vector3( 1, 0, 0 ), -1.57079633);
					mesh.geometry.center()
				
					mesh.updateMatrixWorld();
					console.log("Setting mesh world position: ", mesh.getWorldPosition())
					render();

					var box = new THREE.Box3().setFromObject(mesh);
					console.log( box.min, box.max, box.getSize(center) );
					objectSize = box.getSize(center);
					fillValue("model_dimension",round(objectSize.x * 10) + " x " + round(objectSize.z * 10) + " x " + round(objectSize.y * 10) + " mm");
					
					var helper = new THREE.Box3Helper( box, 0xffff00 );
					scene.add( helper );
					
					mesh.castShadow = true;
					mesh.receiveShadow = true;
					scene.add( mesh );

					controls.target = mesh.getWorldPosition();
					
				} );


				// Lights
				scene.add( new THREE.HemisphereLight( 0x898989, 0x3f3f3f, 2) );
				addShadowedLight( -50, 30, -100, 0xfafafa, 1 );
				addShadowedLight( 50, -10, 100, 0xcccccc, 0.6);

				//Create renderer
				renderer = new THREE.WebGLRenderer( { antialias: true } );
				renderer.setPixelRatio( window.devicePixelRatio );
				renderer.setSize( window.innerWidth, window.innerHeight );

				renderer.gammaInput = true;
				renderer.gammaOutput = true;

				renderer.shadowMap.enabled = true;

				container.appendChild( renderer.domElement );

				window.addEventListener( 'resize', onWindowResize, false );
				controls = new THREE.OrbitControls( camera, renderer.domElement );
				controls.minDistance = 3;
				controls.maxDistance = 100;
				controls.update();
			}

			function addShadowedLight( x, y, z, color, intensity ) {

				var directionalLight = new THREE.DirectionalLight( color, intensity );
				directionalLight.position.set( x, y, z );
				scene.add( directionalLight );

				directionalLight.castShadow = true;

				var d = 1;
				directionalLight.shadow.camera.left = - d;
				directionalLight.shadow.camera.right = d;
				directionalLight.shadow.camera.top = d;
				directionalLight.shadow.camera.bottom = - d;

				directionalLight.shadow.camera.near = 1;
				directionalLight.shadow.camera.far = 4;

				directionalLight.shadow.mapSize.width = 1024;
				directionalLight.shadow.mapSize.height = 1024;

				directionalLight.shadow.bias = - 0.002;

			}

			function setMeshToWireframe(isWireframe){
				if (isWireframe){
					stlMesh.material = outlineMaterial;
				}else{
					stlMesh.material = mainMaterial;
				}
			}

			function onWindowResize() {

				camera.aspect = window.innerWidth / window.innerHeight;
				camera.updateProjectionMatrix();

				renderer.setSize( window.innerWidth, window.innerHeight );

			}

			function animate() {
				requestAnimationFrame( animate );
				render();

			}

			function render() {

				var timer = Date.now() * 0.0005;

				//camera.position.x = Math.cos( timer ) * 3;
				//camera.position.z = Math.sin( timer ) * 3;

				//camera.lookAt( cameraTarget );
				controls.update();
				renderer.render( scene, camera );

			}
			
			/*
			var fov = camera.fov, zoom = 1.0, inc = -0.05;
			$(document).bind('mousewheel DOMMouseScroll', function(event){
				if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
					// scroll up --> Zoom in
					if (camera.fov > 1){
						camera.fov = fov * zoom;
						camera.updateProjectionMatrix();
						zoom += inc;
					}else{
						//Cannot be zoomed in anymore!
					}
				}
				else {
					if (camera.fov < 100){
						// scroll down --> Zoom out
						camera.fov = fov * zoom;
						camera.updateProjectionMatrix();
						zoom -= inc;
					}else{
						//Cannot be zoomed out anymore!
					}
					
					
				}
			});
			*/
			
			 
		</script>
	</body>
</html>
